package cn.zmit.kuxi.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.zmit.kuxi.R;
import cn.zmit.kuxi.adapter.ExpressRecyAdapter;
import cn.zmit.kuxi.adapter.ExpressRecyAdapter.OnItemClickListener;
import cn.zmit.kuxi.contants.Response;
import cn.zmit.kuxi.contants.SPConstants;
import cn.zmit.kuxi.contants.Url;
import cn.zmit.kuxi.entity.ExpressEntity;
import cn.zmit.kuxi.image.ImageDisplayer;
import cn.zmit.kuxi.request.RequestTask;
import cn.zmit.kuxi.utils.HttpClientUtils;
import cn.zmit.kuxi.widget.wheel.OnWheelChangedListener;
import cn.zmit.kuxi.widget.wheel.WheelView;
import cn.zmit.kuxi.widget.wheel.adapters.ArrayWheelAdapter;

import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.xdroid.common.utils.PreferenceHelper;
import com.xdroid.common.utils.ToastUtils;
import com.xdroid.functions.request.JsonData;
import com.xdroid.request.extension.XDroidRequest;
import com.xdroid.request.extension.config.DataType;
import com.xdroid.request.extension.impl.OnRequestListenerAdapter;

/** * @author @parameter * @return */
public class UserInfoActivity extends BaseActivity implements
		OnWheelChangedListener {
	@ViewInject(R.id.imag_user_info_pic)
	private ImageView imag_user_info_pic;
	@ViewInject(R.id.tv_user_info_name)
	private EditText edit_user_info_name;
	@ViewInject(R.id.tv_user_info_num)
	private TextView tv_user_info_num;
	@ViewInject(R.id.tv_user_info_address)
	private TextView tv_user_info_address;
	@ViewInject(R.id.ed_user_info__detail_address)
	private EditText ed_user_info__detail_address;
	@ViewInject(R.id.iamg_user_info_next1)
	private ImageView iamg_user_info_next1;
	@ViewInject(R.id.iamg_user_info_next4)
	private ImageView iamg_user_info_next4;
	@ViewInject(R.id.btn_save_set)
	private Button btn_save_set;
	@ViewInject(R.id.rl_dialog_ios_7_root)
	private RelativeLayout mDialogRootRelativeLayout;

	@ViewInject(R.id.ll_dialog_ios_7_cotent)
	private LinearLayout mDialogCotentLinearLayout;
	WheelView mViewProvince, mViewCity, mViewDistrict;
	Dialog dialog;
	String addres;
	String name = "";
	String userPic;
	private String userId, user_address = "", detailsAddress = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitleView("个人资料", true);
		setContentView(R.layout.activity_user_info);
		ViewUtils.inject(this);
		initView();
	}

	private void initView() {
		edit_user_info_name.setText(getTextFromBundle("name"));
		tv_user_info_num.setText(getTextFromBundle("phone"));
		userPic = getTextFromBundle("userPic");
		userId = getTextFromBundle("userId");

		if (userPic != null) {
			ImageDisplayer.getInstance().dispalyImageWithRadius(
					Url.IMAGR_ROOT + userPic, imag_user_info_pic, 0);
		} else {
			imag_user_info_pic.setImageResource(R.drawable.ic_launcher);
		}

		// user_address = tv_user_info_address.getText().toString().trim();
		//
		// addres = PreferenceHelper.readString(context,
		// SPConstants.SHARED_PREFERENCE_NAME, SPConstants.ADDRESS, "");
		// if (addres != null && addres.length() > 0) {
		// tv_user_info_address.setText(addres);
		// }
		// String addressDetails = PreferenceHelper.readString(context,
		// SPConstants.SHARED_PREFERENCE_NAME, SPConstants.ADDRESSDETAIL,
		// "");
		// if (addressDetails != null && addressDetails.length() > 0) {
		// ed_user_info__detail_address.setText(addressDetails);
		// }

		RequestParams params = new RequestParams();
		params.add("user_id", userId);
		HttpClientUtils.getInstance().post(Url.USERINFODETAIL, params,
				new MyResponseHandler());
	}

	private String area;
	private String address;

	class MyResponseHandler extends AsyncHttpResponseHandler {

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {
			Toast.makeText(context, "网络错误", 0).show();
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			String response = new String(arg2);
			if (response != null) {
				// try {
				// JSONObject root = new JSONObject(response);
				// JSONArray arr = root.getJSONArray("user_info");
				// if (arr != null && arr.length() > 0) {
				// for (int i = 0; i < arr.length(); i++) {
				// JSONObject obj = arr.getJSONObject(i);
				// area = obj.getString("area");
				// address = obj.getString("address");
				// }
				// }
				//
				// } catch (JSONException e) {
				// e.printStackTrace();
				// }
				JsonData jsondata = JsonData.create(response);
				JsonData data = jsondata.optJson("user_info");
				area = data.optString("area");
				address = data.optString("address");
			}
			tv_user_info_address.setText(area);
			ed_user_info__detail_address.setText(address);
		}
	}

	@SuppressWarnings("unused")
	@OnClick({ R.id.rl_user_info_next1, R.id.imag_user_info_pic,
			R.id.rl_user_info_next2, R.id.btn_save_set,
			R.id.rl_iamg_user_info_next4, R.id.tv_select_camera,
			R.id.tv_select_gallery, R.id.tv_cancel, R.id.rl_dialog_ios_7_root,
			R.id.ll_dialog_ios_7_cotent })
	private void OnClick(View v) {
		switch (v.getId()) {
		case R.id.rl_user_info_next1:// 号码设置
			openActivityForResault(SetNumActivity.class, 1);
			break;
		case R.id.rl_user_info_next2:// 地址设置
			dialog = new Dialog(UserInfoActivity.this,
					R.style.style_custom_dialog);
			View view = View.inflate(UserInfoActivity.this,
					R.layout.dialog_select_address, null);
			mViewProvince = (WheelView) view.findViewById(R.id.id_province);
			mViewCity = (WheelView) view.findViewById(R.id.id_city);
			mViewDistrict = (WheelView) view.findViewById(R.id.id_district);
			TextView tv_done = (TextView) view.findViewById(R.id.tv_done);

			setUpListener();
			setUpData();
			tv_done.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					tv_user_info_address.setText(mCurrentProviceName
							+ mCurrentCityName + mCurrentDistrictName);
					PreferenceHelper.write(context,
							SPConstants.SHARED_PREFERENCE_NAME,
							SPConstants.ADDRESS, mCurrentProviceName
									+ mCurrentCityName + mCurrentDistrictName);
					area = mCurrentProviceName + mCurrentCityName
							+ mCurrentDistrictName;
					dialog.dismiss();
				}
			});
			dialog.setContentView(view);
			dialog.show();
			WindowManager m = getWindowManager();
			Display d = m.getDefaultDisplay(); // 为获取屏幕宽、高
			android.view.WindowManager.LayoutParams p = dialog.getWindow()
					.getAttributes(); // 获取对话框当前的参数值
			p.width = (int) (d.getWidth()); // 宽度设置为全屏
			dialog.getWindow().setAttributes(p); // 设置生效

			break;
		case R.id.rl_iamg_user_info_next4:// 密码设置

			openActivity(PasswordSet.class);
			break;
		case R.id.btn_save_set:// 保存修改
			user_address = tv_user_info_address.getText().toString().trim();

			detailsAddress = ed_user_info__detail_address.getText().toString()
					.trim();
			name = edit_user_info_name.getText().toString().trim();
			PreferenceHelper.write(context, SPConstants.SHARED_PREFERENCE_NAME,
					SPConstants.ADDRESSDETAIL, detailsAddress);

			address = ed_user_info__detail_address.getText().toString().trim();
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("user_id", userId);
			map.put("area", area);
			map.put("name", name);
			map.put("address", address);
			if (fileSrc != null && fileSrc.length() > 0) {
				saveBitmap2file(img, fileSrc);
				File file = new File(fileSrc);
				map.put("avatar", file);
			}

			RequestTask.getInstance().doUserinfoEdit(this, map,
					new UserInfoonRequestListener());

			break;
		case R.id.imag_user_info_pic:// 头像设置
			openDialog();
			break;
		case R.id.tv_select_camera:// 相机
			closeDialog();
			// 设置相机拍照后照片保存路径
			pictureFile = new File(Environment.getExternalStorageDirectory(),
					"picture" + System.currentTimeMillis() / 1000 + ".jpg");
			// 启动拍照,并保存到临时文件
			Intent intentCam = new Intent();
			intentCam.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
			intentCam.putExtra(MediaStore.EXTRA_OUTPUT,
					Uri.fromFile(pictureFile));
			intentCam.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
			startActivityForResult(intentCam, REQUEST_CAMERA_IMAGE);
			break;
		case R.id.tv_select_gallery:// 相册·
			closeDialog();
			Intent intentCho = new Intent();
			intentCho.setType("image/*");
			intentCho.setAction(Intent.ACTION_PICK);
			startActivityForResult(intentCho, REQUEST_PICTURE_CHOOSE);
			break;
		case R.id.tv_cancel:// 取消
			closeDialog();
			break;
		case R.id.rl_dialog_ios_7_root://
			closeDialog();
			break;
		default:
			break;
		}
	}

	// 保存请求
	private class UserInfoonRequestListener extends
			OnRequestListenerAdapter<Object> {
		@Override
		public void onDone(XDroidRequest<?> request, String response,
				DataType dataType) {
			super.onDone(request, response, dataType);
			dismissProgressDialog();
			JsonData jsonData = JsonData.create(response);
			String avatar_error = jsonData.optString("avatar_error");
			if (jsonData.optString(Response.CODE).equals("1")) {
				if (!TextUtils.isEmpty(avatar_error)) {
					ToastUtils.show(context, "头像图片过大");
				} else {
					ToastUtils.show(context, "信息已提交");
					finish();
				}
			} else {
				ToastUtils.show(context, "提交失败！请重试");
			}

		}

		@Override
		public void onRequestPrepare() {
			super.onRequestPrepare();
			showProgressDialog("正在提交……");
		}

		@Override
		public void onRequestFailed(String error) {
			super.onRequestFailed(error);
			dismissProgressDialog();
		}
	}

	private void setUpData() {
		initProvinceDatas();
		mViewProvince.setViewAdapter(new ArrayWheelAdapter<String>(
				UserInfoActivity.this, mProvinceDatas));
		// 设置可见条目数量
		mViewProvince.setVisibleItems(7);
		mViewCity.setVisibleItems(7);
		mViewDistrict.setVisibleItems(7);
		updateCities();
		updateAreas();
	}

	// 添加change事件
	private void setUpListener() {
		mViewProvince.addChangingListener(this);
		mViewCity.addChangingListener(this);
		mViewDistrict.addChangingListener(this);
	}

	String phone = null;

	// 头像xuanze
	private void openDialog() {
		performDialogAnimation(mDialogRootRelativeLayout,
				mDialogCotentLinearLayout, true);
	}

	private void closeDialog() {
		performDialogAnimation(mDialogRootRelativeLayout,
				mDialogCotentLinearLayout, false);
	}

	// @Override
	// public void onChanged(WheelView wheel, int oldValue, int newValue) {
	// if (wheel == mViewProvince) {
	// updateCities();
	// } else if (wheel == mViewCity) {
	// updateAreas();
	// } else if (wheel == mViewDistrict) {
	// mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[newValue];
	// mCurrentZipCode = mZipcodeDatasMap.get(mCurrentDistrictName);
	// }
	// }

	@Override
	public void onChanged(WheelView wheel, int oldValue, int newValue) {
		if (wheel == mViewProvince) {
			updateCities();
		} else if (wheel == mViewCity) {
			updateAreas();
		} else if (wheel == mViewDistrict) {
			updateDistrict();

		}

	}

	/**
	 * 根据当前的省，更新市WheelView的信息
	 */
	private void updateCities() {
		int pCurrent = mViewProvince.getCurrentItem();
		mCurrentProviceName = mProvinceDatas[pCurrent];

		String[] cities = mCitisDatasMap.get(mCurrentProviceName);
		if (cities == null) {
			cities = new String[] { "" };
		}
		mViewCity.setViewAdapter(new ArrayWheelAdapter<String>(this, cities));
		mViewCity.setCurrentItem(0);
		updateAreas();

	}

	/**
	 * 根据当前的市，更新区WheelView的信息
	 */
	private void updateAreas() {
		int pCurrent = mViewCity.getCurrentItem();
		mCurrentCityName = mCitisDatasMap.get(mCurrentProviceName)[pCurrent];
		String[] areas = mDistrictDatasMap.get(mCurrentCityName);

		if (areas == null) {
			areas = new String[] { "" };
		}
		mViewDistrict
				.setViewAdapter(new ArrayWheelAdapter<String>(this, areas));
		mViewDistrict.setCurrentItem(0);
		updateDistrict();
	}

	private void updateDistrict() {
		int pCurrent = mViewDistrict.getCurrentItem();
		mCurrentDistrictName = mDistrictDatasMap.get(mCurrentCityName)[pCurrent];
		// mCurrentDistrictId =
		// mDistrictDatasMapId.get(mCurrentCityId)[pCurrent];
	}

	@Override
	protected void onResume() {
		phone = PreferenceHelper.readString(context, "phone",
				SPConstants.PHONE, null);
		tv_user_info_num.setText(phone);
		super.onResume();
	}

	/**
	 * @author Joash_Yan
	 */
	// 这是选图和拍照相关
	private static final int REQUEST_PICTURE_CHOOSE = 1;
	private static final int REQUEST_CAMERA_IMAGE = 2;
	private File pictureFile;
	private Bitmap img = null;
	private byte[] imgData = null;
	static String fileSrc = null;

	/**
	 * 返回选图或者拍照的结果
	 * 
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK) {
			return;
		}

		if (requestCode == REQUEST_PICTURE_CHOOSE) {
			if ("file".equals(data.getData().getScheme())) {
				// 有些低版本机型返回的Uri模式为file
				fileSrc = data.getData().getPath();
			} else {
				// Uri模型为content
				String[] proj = { MediaStore.Images.Media.DATA };
				Cursor cursor = getContentResolver().query(data.getData(),
						proj, null, null, null);
				cursor.moveToFirst();
				int idx = cursor
						.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
				fileSrc = cursor.getString(idx);
				cursor.close();
			}
		} else if (requestCode == REQUEST_CAMERA_IMAGE) {
			if (null == pictureFile) {
				Toast.makeText(context, "拍照失败，请重试", 0).show();
				return;
			}

			fileSrc = pictureFile.getAbsolutePath();
			updateGallery(fileSrc);
		}
		// 获取图片的宽和高
		Options options = new Options();
		options.inJustDecodeBounds = true;
		img = BitmapFactory.decodeFile(fileSrc, options);

		// 压缩图片
		options.inSampleSize = Math.max(1, (int) Math.ceil(Math.max(
				(double) options.outWidth / 1024f,
				(double) options.outHeight / 1024f)));
		options.inJustDecodeBounds = false;
		img = BitmapFactory.decodeFile(fileSrc, options);

		// 部分手机会对图片做旋转，这里检测旋转角度
		int degree = readPictureDegree(fileSrc);
		if (degree != 0) {
			// 把图片旋转为正的方向
			img = rotateImage(degree, img);
		}

		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		// 可根据流量及网络状况对图片进行压缩
		img.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		imgData = baos.toByteArray();

		((ImageView) findViewById(R.id.imag_user_info_pic)).setImageBitmap(img);
	}

	/**
	 * 读取图片属性：旋转的角度
	 * 
	 * @param path
	 *            图片绝对路径
	 * @return degree旋转的角度
	 */
	public static int readPictureDegree(String path) {
		int degree = 0;
		try {
			ExifInterface exifInterface = new ExifInterface(path);
			int orientation = exifInterface.getAttributeInt(
					ExifInterface.TAG_ORIENTATION,
					ExifInterface.ORIENTATION_NORMAL);
			switch (orientation) {
			case ExifInterface.ORIENTATION_ROTATE_90:
				degree = 90;
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				degree = 180;
				break;
			case ExifInterface.ORIENTATION_ROTATE_270:
				degree = 270;
				break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return degree;
	}

	/**
	 * 
	 * 
	 * @param filename
	 */
	private void updateGallery(String filename) {
		MediaScannerConnection.scanFile(this, new String[] { filename }, null,
				new MediaScannerConnection.OnScanCompletedListener() {

					@Override
					public void onScanCompleted(String arg0, Uri arg1) {
						Log.e("successed===", "userinfo_gallery");
					}
				});
	}

	/**
	 * 旋转图片
	 * 
	 * @param angle
	 * @param bitmap
	 * @return Bitmap
	 */
	public static Bitmap rotateImage(int angle, Bitmap bitmap) {
		// 图片旋转矩阵
		Matrix matrix = new Matrix();
		matrix.postRotate(angle);
		// 得到旋转后的图片
		Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
				bitmap.getWidth(), bitmap.getHeight(), matrix, true);
		return resizedBitmap;
	}

	// saveBitmap2file
	static boolean saveBitmap2file(Bitmap bmp, String filename) {
		CompressFormat format = Bitmap.CompressFormat.JPEG;
		int quality = 50;
		OutputStream stream = null;
		try {
			stream = new FileOutputStream(fileSrc);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

		return bmp.compress(format, quality, stream);
	}
}